package web_programing.review.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;

/**
 * @author haomin
 * @date 2022/09/26 09:56
 **/
public class Client2 {
    public static void main(String[] args) throws IOException {
        // 自己的云服务器：
        // 目前服务器在本机: 43.142.***.***
        // 目前服务器的端口是: 8088

        // 目前只发送一次请求
        //String word = "apple";
        String word = "apple";

        // 准备发送请求
        String request = "请求格式头\r\n" + word + "请求格式尾\r\n";
        byte[] bytes = request.getBytes("UTF-8");
        DatagramPacket sent = new DatagramPacket(
                bytes, 0, bytes.length,
                // 43.142.***.***
                InetAddress.getByAddress(new byte[]{(byte)43,(byte)142,(byte)133,(byte)216 }),
                8088
        );
        DatagramSocket socket = new DatagramSocket(9999);
        Log.println("发送请求");
        socket.send(sent);

        byte[] buf = new byte[1024];
        DatagramPacket received = new DatagramPacket(buf, buf.length);
        socket.receive(received);
        int n = received.getLength();
        String response = new String(buf, 0, n, "utf-8");
        System.out.println(response);
    }
}